<?php
/**
 * Created by PhpStorm.
 * User: Merdan
 * Date: 2017/3/28
 * Time: 13:27
 */

namespace App\Services;
use App\Exceptions\NotExistException;
use App\Models\Category as CategoryModel;

class Category extends BaseService
{
    /**
     * 分类列表
     *
     * @param $limit
     * @param null $name
     * @return mixed
     */
    public function getList($limit, $name = null)
    {
        $categories = CategoryModel::select()->withCount('product');
        if($name !== null){
            $categories->where('name', 'like', "%$name%");
        }
        return $categories->paginate($limit);
    }

    /**
     * 获取单个分类数据
     *
     * @param $id
     * @return mixed
     * @throws NotExistException
     */
    public function show($id)
    {
        $canteen = CategoryModel::find($id);
        if(!$canteen) throw new NotExistException('你查看的分类不存在');
        return $canteen;
    }

    /**
     * 创建新的分类
     *
     * @param $data
     * @return CategoryModel
     */
    public function create($data)
    {
        return CategoryModel::create($data);
    }

    /**
     * 更新分类
     *
     * @param $id
     * @param $data
     * @return CategoryModel
     * @throws NotExistException
     */
    public function update($id, $data)
    {
        $canteen = CategoryModel::find($id);
        if(!$canteen) throw new NotExistException('你查看的分类不存在');
        $data = array_filter($data, function ($item){
            return $item != null;
        });
        if(count($data) > 0){
            $canteen->update($data);
        }
        return $canteen;
    }
}